using LiJ.Common.Encrypt;
using LiJ.Common.Extention;
using System;
using System.Threading;

namespace LiJ.Common.Authrization
{
	/// <summary>
	/// 当前系统访问上下文信息
	/// </summary>
	public static class MemberShiper
	{
		private static readonly AsyncLocal<AppAuthorizeInfo> _appAuthorize = new AsyncLocal<AppAuthorizeInfo>();

		private static readonly AsyncLocal<MemberIdentity> _identity = new AsyncLocal<MemberIdentity>();

		/// <summary>
		///   应用授权信息
		/// </summary>
		public static AppAuthorizeInfo AppAuthorize => _appAuthorize.Value;

	    /// <summary>
		///   成员身份信息
		/// </summary>
		public static MemberIdentity Identity => _identity.Value;

	    /// <summary>
		/// 是否已经验证
		/// </summary>
		public static bool IsAuthenticated => _identity.Value != null;

	    /// <summary>
		///   设置用户信息
		/// </summary>
		/// <param name="info"></param>
		public static void SetIdentity(MemberIdentity info)
		{
            _identity.Value = info;
		}

		/// <summary>
		///   设置应用授权信息
		/// </summary>
		/// <param name="info"></param>
		public static void SetAppAuthrizeInfo(AppAuthorizeInfo info)
		{
            _appAuthorize.Value = info;
		}

		/// <summary>
		/// 获取成员扩展详情
		/// </summary>
		/// <typeparam name="TMInfo"></typeparam>
		/// <returns></returns>
		public static TMInfo GetMemberInfo<TMInfo>() where TMInfo : class
		{
			MemberIdentity value = _identity.Value;
			return value?.MemberInfo as TMInfo;
		}

		/// <summary>
		/// 通过 ID 生成对应的Token
		/// </summary>
		/// <param name="encryptKey"></param>
		/// <param name="tokenDetail"></param>
		/// <returns></returns>
		public static string GetToken(string encryptKey, string tokenDetail)
		{
			return AesRijndael.Encrypt(tokenDetail, encryptKey).Base64UrlEncode();
		}

		/// <summary>
		///  通过token解析出对应的id和key
		/// </summary>
		/// <param name="encryptKey"></param>
		/// <param name="token"></param>
		/// <returns>返回解析信息，Item1为id，Item2为key</returns>
		public static string GetTokenDetail(string encryptKey, string token)
		{
			string text = AesRijndael.Decrypt(token.Base64UrlDecode(), encryptKey);
			if (string.IsNullOrEmpty(text))
			{
				throw new ArgumentNullException("token", "不合法的用户Token");
			}
			return text;
		}
	}
}
